<?php
/**
 * Created by JetBrains PhpStorm.
 * User: cgp
 * Date: 13-4-17
 * Time: 上午11:23
 * To change this template use File | Settings | File Templates.
 */

class TicketC {
    /**
     * 新增、更新票类
     *
     * @param $lid
     * @param $applyid
     * @param int $tid
     * @param \pft\Prod\Product $pobj
     * @return array|mixed
     */
    public function AddTicket($lid, $applyid, $tid=0, \pft\Prod\Product $pobj) {
        $jData = array();
        $ptype = $_POST['ptype'];
        $jData['title'] = !$tid && p_match($_POST['tTitle']) ?
            exit('{"msg":"门票标题含有非法字符"}') : safetxt($_POST['tTitle']);
        $jData['landid'] = $lid;
        if( !$tid || ($tid>0 && isset($_POST['price1']) ) ) {
            //如果是更新，可以不更改门市价——2013年9月22日15:23:49
            $jData['tprice'] = !$_POST['price1']?
                exit('{"msg":"门市价必须大于0"}'):abs($_POST['price1']);//门市价
        }
        //$jData['storage'] = abs($_POST['storage']);//库存
        $jData['pay'] = abs($_POST['payType']);//支付方式
        $jData['ifs'] = abs($_POST['ticketMedia']);//门票介质0电子票1实体票
        $jData['uuid'] = isset($_POST['uuid']) ? safetxt($_POST['uuid']) : '';
		
		
        //允许推迟游玩天数
        
        $jData['delaydays'] = ($_POST['validTime'] == 1 || $_POST['validTime'] ==2) ? abs($_POST['vt']):0;
        
        $jData['ddays'] = abs($_POST['earyTime']);//提前下单时间
		$jData['max_order_days'] = $_POST['max_days'] ? $_POST['max_days']:'-1';
        $jData['getaddr'] = safetxt($_POST['TicketInfo']);//取票信息
        $jData['notes'] = safetxt($_POST['TicketExplain']);//购票须知
//        $jData['s_limit_up']    = abs($_POST['slimit_up']); //库存上限
        //$jData['s_limit_up']    = $jData['storage']; //库存上限
        //$jData['s_limit_low']   = abs($_POST['slimit_low']); //库存下限
        $jData['buy_limit_up']  = abs($_POST['blimit_up']);//  //购买上限
        $jData['buy_limit_low'] = is_numeric($_POST['blimit_low']) &&
            $_POST['blimit_low']>=0 ? $_POST['blimit_low'] :
            exit('{"msg":"购买下限不能小于0"}');//购买下限
        if(!empty($_POST['otime']) && !empty($_POST['etime'])) {
            $t1 = strtotime($_POST['otime']);
            $t2 = strtotime($_POST['etime']);
            if($t1>$t2) {
                echo '{"msg":"截至日期不能小于启用日期"}';
                exit;
            }
            else {
                $jData['open_time']     = trim($_POST['otime']);//启用日期
                $jData['end_time']      = trim($_POST['etime']);//结束日期
            }
        }
        //闸机绑定
		$jData['sourceT'] = 0;
		if(isset($_POST['gate'])) $jData['uuid'] = $_POST['gate'];
		if(isset($_POST['gate']) && $_POST['gate']!=''){
			$sql = "select jiutian_auth from pft_member_extinfo where fid={$_SESSION['sid']} limit 1";
			$GLOBALS['le']->query($sql);
			$GLOBALS['le']->fetch_assoc();
			if($GLOBALS['le']->f('jiutian_auth')) $jData['sourceT'] = 1;
		} 
		
		
        $jData['apply_did']  = $applyid;//分销商id
        //$jData['status'] = abs($_POST['c_status']);//确认订单0不需确认，1需要确认
        $dprice = 0;
        //dev begin
        $fData = array();//景区扩展表存储数据
        $sfData = $_POST['f'];
        //$jData['status'] = intval($_POST['auto_c']);//订单退改0无需审核1需审核
        $jData['reb_type'] = $_REQUEST['reb_type'];// 取消费用类型 0 百分比 1 实际值
        if($jData['reb_type']==1){
            $jData['reb'] = $_POST['reb']*100;
        }else{
            if($jData['reb']>100 || $jData['reb']<0 ) 
            exit('{"msg":"取消费用百分比值必须在 0 到 100"}');
            $jData['reb'] = intval($_POST['reb']);//消订单需要收取的费用百分比 0不收取
        }
        
        $jData['cancel_auto_onMin'] = abs($_POST['cancel_time']); // 未支付多少分钟内自动取消
        $jData['order_end'] = '';
        $jData['order_start'] = '';
        if($_POST['validTime'] == 1){ // 推迟类型 0 游玩 1 下单之后
            $jData['delaytype'] = 0;
        }elseif($_POST['validTime'] == 2){
            $jData['delaytype'] = 1;
        }elseif($_POST['validTime']==3){
			$endDate = $_POST['order_end'];// 订单截止有效日期
			if($endDate!=''){
				if($endDate<date('Y-m-d')) $endDate = date('Y-m-d');
				$jData['order_end'] = $endDate.' 23:59:59';
			}else{
				$jData['order_end'] = date('Y-m-d 23:59:59');
			}
			
			$startDate = $_POST['order_start'];// 订单开始有效时间
			if($startDate!=''){
				if($startDate>$endDate) $startDate = $endDate;
				if($startDate<date('Y-m-d')) $startDate = date('Y-m-d');
				$jData['order_start'] = $startDate.' 00:00:00'; 
			}else{
				$jData['order_start'] = date('Y-m-d');
			}
			
			
             
        }else{
            $jData['delaytype'] = 0;
        }
		
		// if($_SESSION['sid']==1433 || $_SESSION['sid']==3385) {
			// $jData['order_start'] =  $_POST['order_start'];
			// $jData['order_end'] =  date('Y-m-d 23:59:59', strtotime($_POST['order_end']));
		// }
		// if($_SESSION['sid']=1433){
			// print_r($_POST);
			// print_r($jData);
			// exit;
		// }
		
        // 验证限制
        if(isset($_REQUEST['verify_limit']) && $_REQUEST['verify_limit']!=''){
            $week = array(1,2,3,4,5,6,7);
            $jData['order_limit'] = implode(',',array_diff($week,$_POST['verify_limit']));
        }else{
            $jData['order_limit'] = '';
        }
       
       // 点评返现 与 取消费用 云顶项目需求
	   /*
        $reb_days = $_POST['reb_days'];
        $reb_cost = $_POST['reb_cost'];
        $reb_dc = array();
        if(count($reb_days)){
            $reb_days = array_unique($reb_days);
            foreach($reb_days as $key=>$val){
                if($val=='' || $reb_cost[$key]=='') continue;
                // $reb_dc[] = array('days'=>$val,'cost'=>$reb_cost[$key]);
                $reb_dc[$val] = $reb_cost[$key];
            }
        }
        if(!empty($reb_dc)) $jData['cancel_cost'] = json_encode($reb_dc);
		*/
		
		$reb_days = $_POST['reb_days'];
        $reb_cost = $_POST['reb_cost'];
        $reb_type = $_POST['reb_type'];
	
        $reb_dc = array();
        if(count($reb_days)){
            $reb_days = array_unique($reb_days);
            foreach($reb_days as $key=>$val){
                if($val=='' || $reb_cost[$key]=='') continue;
                $reb_dc[] = array(
					'c_type'=>$reb_type[$key],
					'c_cost'=>$reb_cost[$key]*100,
					'c_days'=>$reb_days[$key]
				);
            }
        }
		if(!empty($reb_dc)) $jData['cancel_cost'] = json_encode($reb_dc);
		// if($_SESSION['sid']==1433) {
			// print_r($_POST);
			// exit($jData['cancel_cost']);
		// }
		
		
        $jData['re_integral'] = $_POST['integral'] + 0;
        
        //景区扩展表ID，大于0为更新
        $fid = isset($sfData['fid']) ? abs($sfData['fid']) : 0;
        $fData['confirm_sms'] = abs($sfData['confirm_sms']);
        /*新加取消短信是否发送通知短信给游客
        * 把cancel_sms 和 confirm_sms 并存在confirm_sms里
        * 二进制转十进制 如果两个值都是1 转成3 都是0 还是0
        * cancel_sms 是高位 confirm_sms 是低位
        * zax 2015-06-16
        */
        $sfData['cancel_sms'] = $sfData['cancel_sms'] ? abs($sfData['cancel_sms']) : 0;//取消是否通知游客
        $fData['confirm_sms'] = bindec($sfData['cancel_sms'].$fData['confirm_sms']);
        $fData['sendVoucher'] = abs($_POST['sendVoucher']);
        //判断是否关注微信帐号
        /*
        if(abs($_POST['confirm_wx'])==1){
            $sel_wx = "select fromusername from uu_wx_member_pft where fid={$_SESSION['sid']} and aid=21207 limit 1";
            $GLOBALS['le']->query($sel_wx);
            $row = $GLOBALS['le']->fetch_assoc();
            if(!$row){
                exit('{"code":107,"msg":"未绑定微信公众号"}');
            }
        }
        */
        $fData['confirm_wx'] = abs($_POST['confirm_wx']);
        $fData['manual_verify'] = abs($sfData['manual_verify']);
        $fData['p_type'] = $ptype;
        $fData['lid'] = $lid;
		
		// 过期是否可退
		$jData['overdue_refund'] = 0;
		if(isset($_POST['overdue_refund'])) $jData['overdue_refund'] = $_POST['overdue_refund']+0;
		
        if (isset($sfData['dmin'])) {
            $fData['dhour'] = ($sfData['dhour'] .':'. $sfData['dmin']) . ':00';//提前预定小时
//            print_r($fData);exit;
        } else {
            $fData['dhour'] = ($sfData['dhour']<10 ? '0'.$sfData['dhour']
                    :$sfData['dhour']) . ':59:00';//提前预定小时
        }
        $fData['tourist_info'] = intval($sfData['tourist_info']);
//        $fData['v_mobile_support'] = intval($sfData['v_mobile_support']);
        $fData['v_ID_support'] = intval($sfData['v_ID_support']);
        if($ptype=='B') {
            $fData['startplace'] = !empty($sfData['beginPlace'])?
                safetxt($sfData['beginPlace']):'';
            $fData['endplace'] =  !empty($sfData['endPlace'])?
                safetxt($sfData['endPlace']):'';
            $fData['rdays'] = abs($sfData['rdays']);//游玩天数
            if(!empty($_POST['grp_num1'])) {
                $grp_num2 = !empty($_POST['grp_num2']) ?
                    '-'.trim($_POST['grp_num2']):'';
                $fData['series_model'] = trim($_POST['grp_num1'])
                                            . '{fck_date}'.$grp_num2;
            }
            if( !strlen( trim($sfData['ass_station']) ) ){
                exit('{"msg":"请至少填写一个集合地点"}');
            }
            $new_ass = array();
            $ass_station = safetxt($sfData['ass_station']);
            $ass_station = str_replace('；',';',$ass_station);
            if(strpos($ass_station,';')) {
                $ass_station = explode(';',str_replace('；',';',$ass_station));
                array_walk($ass_station,'plus_key',array(&$new_ass));
            }
            else {
                $new_ass = array(1=>$ass_station);
            }
            $fData['ass_station'] = serialize($new_ass);
        }
        elseif ($ptype=='A') {
            if ($fid>0) {
                $vt = intval($_POST['v_time_limit']);
                if ($vt==1) {
                    $vt1 = trim($_POST['vt1']);
                    $vt2 = trim($_POST['vt2']);
                    if ($vt1 == $vt2) {
                        exit('{"msg":"验证时间至少间隔1小时"}');
                    }
                    $fData['v_time_limit'] = $vt1.'|'.$vt2;
                } else {
                    $fData['v_time_limit'] = 0;
                }
            } else {
                $fData['v_time_limit'] = $sfData['v_time_limit'];
            }

        }
		if($ptype=='H'){
			$fData['zone_id'] = $_POST['zone_id']+0;
			// if($fData['zone_id']==0) exit('{"msg":"请关联场馆分区"}');
		}
		// 是否开启景点类别属性
		if(isset($_POST['mdetails'])) $jData['Mdetails'] = $_POST['mdetails']+0;
		if(isset($_POST['mpath']))    $jData['Mpath']    = $_POST['mpath'];

        //保存数据
        if(!empty($_POST['tid'])  && empty($_POST['iscopy'])) {
			// $jData['p_status'] = $_POST['provide2']+0;
            //TODO:更新门票
            $res = $pobj->UpdateTicket($jData, abs($_POST['tid']));
            //print_r($res);
        }
        else {
            //TODO:添加门票,如果有特价票，添加成功后保存特价票
            $res = $pobj->AddTickets($jData,$dprice);
            // print_r($res);
            // exit;
            //更新产品销售范围BEGIN——2013年9月14日9:48:51
            $provide_to = intval($_POST['provide_to']);
            $saleTime = intval($_POST['saleTime']);
            $pobj->UpdateSuperProduct($provide_to, $saleTime,$res['pid']);
            //更新产品销售范围END
        }
        if($res['errcode']!=1000){
            return $res;
        }

        $fData['tid'] = $res['lastid'];
        $fData['pid'] = $res['pid'];

//        print_r($fData);
        if( $pobj->ProductExt($fData, $fid) ) {
//            print_r($fData);
            return $res;
        }
        else {
            return array('errcode'=>1003,'msg'=>"写入数据到产品扩展表失败");
        }
    }
    /**
     * 特价配置
     *
     * @param $pid  产品ID
     * @param $post 价格值
     * @param $rid 动态价格ID
     * @param SoapClient $soap
     * @param int $pft_rflex_id 分销平台（16u.cc）关联产品ID
     * @param SoapClient $soap16u
     * @return mixed|string
     * last update： 2013年12月5日 15:19:36
     */
    public function AddPrice($pid, $post,$rid,SoapClient $soap,
                             $pft_rflex_id=0, SoapClient $soap16u=null,
                             $sync_id=0, $sync_status=0)
    {
       // exit;
        //print_r($post);exit;
        $ptype = abs($post['usedTime']);
        $startdate = !empty($post['bt']) && checkData($post['bt']) ? $post['bt']
            : exit('{"errcode":1007,"msg":"起始日期格式错误！'.$post['bt'].'"}');
        $enddate = !empty($post['et']) && checkData($post['et']) ? $post['et']
            : exit('{"errcode":1007,"msg":"结束日期格式错误！"}');
        $memo = safetxt($post['pexplain']);//说明
        if(strtotime($post['bt'])>strtotime($post['et'])) {
            return '{"errcode":1007,"msg":"结束日期不能小于开始日期"}';
        }
        $ondays = is_array($post['normalDay'])?implode(',',$post['normalDay'])
            :'0,1,2,3,4,5,6';
        $pg = abs($post['pg'])*100;//供货价
        $pl = abs($post['pl'])*100;//零售价
        if( !is_numeric($post['storage']) ) {
            $storage = -1;
        }
        else{
            $storage = $post['storage'];
        }
        if( $storage<-1) {
            return '{"errcode":1007,"msg":"日库存只能为大于等于“-1”的数字！"}';
        }
        if($pl < $pg) {
            return  '{"errcode":1007,"msg":"零售价不能小于供货价！"}';
        }

        return Price::DynamicPriceStatic($pid, $startdate, $enddate, $pg, $pl,
            $ptype, $rid, $memo, $ondays, $soap, $storage, $pft_rflex_id,
            $soap16u,false, $sync_id, $sync_status);//100 ok
    }

}